package com.demo.result;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Date;

/**
 * @author yl
 * @description 定义统一返回
 * @date 2020/11/17 14:00
 */
@Data
@Builder
@Accessors(chain = true)
public class ApiResult<T> implements Serializable {

    /**
     * 响应码
     */
    private int code;
    /**
     * 响应消息
     */
    private String message;
    /**
     * 响应数据
     */
    private T data;

    /**
     * 响应时间
     */
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
    private Date time;

    public static ApiResult ok() {
        return ok(ApiCode.SUCCESS);
    }

    public static <T> ApiResult<T> ok(T data) {
        return result(ApiCode.SUCCESS, data);
    }


    public static ApiResult ok(ApiCode apiCode) {
        return result(apiCode);
    }

    public static <T> ApiResult ok(ApiCode apiCode, T data) {
        return result(apiCode, data);
    }

    public static ApiResult fail() {
        return result(ApiCode.FAIL, null);
    }

    public static ApiResult fail(ApiCode apiCode) {
        return result(apiCode, null);
    }

    public static ApiResult fail(String message) {
        return result(message, ApiCode.FAIL, null);

    }

    public static <T> ApiResult<T> fail(T data, String message) {

        return result(message, ApiCode.FAIL, data);
    }


    public static ApiResult result(ApiCode apiCode) {
        return result(apiCode.getMessage(), apiCode, null);
    }

    public static <T> ApiResult<T> result(ApiCode apiCode, T data) {
        return result(apiCode.getMessage(), apiCode, data);
    }

    public static <T> ApiResult<T> result(String message, ApiCode apiCode, T data) {
        return (ApiResult<T>) ApiResult.builder()
                .code(apiCode.getCode())
                .message(message)
                .data(data)
                .time(new Date())
                .build();
    }
}
